<?php
/**
 * TinyCorePHP 分页类
 * @author 	kelecode@gmail.com
 * @date 	2013-02-17
 */
class TinyPage{

    public $parameter;
    public $varPage = 'p';
    public $totalRows;
    public $pageSize = 10;
    public $totalPage;
    public $currentPage;
    public $tmpl = array(
        'firstPage' => '首页',
        'prePage' => '上一页',
        'nextPage' => '下一页',
        'lastPage' => '尾页',
    );

    public function __construct($totalRows,$pageSize=10,$tmpl=null){
        $this->totalRows = (int)$totalRows;
        $this->pageSize = (int)$pageSize <= 0 ? $this->pageSize : (int)$pageSize;
        $this->tmpl = empty($tmpl) ? $this->tmpl : $tmpl;
        $this->totalPage = ceil($this->totalRows / $this->pageSize);
        $this->currentPage = (int)$_GET['p'];
        $this->currentPage = $this->currentPage <= 0 ? 1 : ($this->currentPage > $this->totalPage ? $this->totalPage : $this->currentPage);
    }

    public function show(){
        if( empty($this->totalRows) ){
            return '';
        }

        $url = $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter;
        $parse = parse_url($url);
        if(isset($parse['query'])) {
            parse_str($parse['query'],$params);
            unset($params[$this->varPage]);
            $url = $parse['path'].'?'.http_build_query($params);
        }

        $html = array();
        //$html[] = $this->totalRows.'条记录';
        //$html[] = $this->currentPage.'/'.$this->totalPage.'页';

        if($this->currentPage > 1){
            $html[] = '<span class="first"><a href="'.$url.'&'.$this->varPage.'=1" style="width:60px;">%firstPage%</a></span>';
            $html[] = '<span class="prev"><a href="'.$url.'&'.$this->varPage.'='.($this->currentPage - 1).'" style="width: 60px;">%prePage%</a></span>';
        }

        for($i=1;$i<=$this->totalPage;$i++){
            $class = $i == $this->currentPage ? 'current' : '';
            if($this->currentPage == $i){
                $html[] = '<span class="page current">'.$i.'</span>';
            }else{
                $html[] = '<span class="page"><a href="'.$url.'&'.$this->varPage.'='.$i.'">'.$i.'</a></span>';
            }
        }

        if($this->currentPage < $this->totalPage){
            $html[] = '<span class="next"><a href="'.$url.'&'.$this->varPage.'='.($this->currentPage + 1).'" style="width: 60px;">%nextPage%</a></span>';
            $html[] = '<span class="last"><a href="'.$url.'&'.$this->varPage.'='.$this->totalPage.'" style="width: 60px;">%lastPage%</a></span>';
        }

        $search = array_map( array('TinyPage','theme'), array_keys($this->tmpl) );
        $replace = array_values($this->tmpl);

        return str_replace( $search,$replace,implode('&nbsp;',$html) );
    }

    public function theme($key){
        return '%'.$key.'%';
    }
}